import { useState, useEffect, useRef } from 'react';
import { Input, message } from 'antd';

export default ({ textNode, otherRules, formatFunc, handleOk, ...props}) => {

  const [editing, setEditing] = useState(false);
  const [value, setValue] = useState(textNode);

  const inputRef = useRef(null);

  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
  };

  const handeSave = (e) => {
    toggleEdit();
    let inputValue = e.target.value?.replaceAll(' ', '');
    if(inputValue == textNode){
      return
    }
    if(typeof otherRules == 'function'){
      if(!otherRules(inputValue)) return;
    }
    if(typeof formatFunc == 'function'){
      inputValue = formatFunc(inputValue);
    };
    if(/\d/.test(inputValue)){
      handleOk(inputValue);
    }
  }

  if(editing){
    return (<>
      <Input {...props} size='small' ref={inputRef} onPressEnter={handeSave} onBlur={handeSave} value={value} onChange={e=>setValue(e.target.value)} status={value || 'error'} />
    </>)
  }

  return <span onClick={toggleEdit} style={{cursor:'pointer',minHeight:'14px'}}>{textNode}</span>
}
